import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { APIBase } from 'app/modules/base/api-base';
import { FormBuilder, Validators } from '@angular/forms';
import { confirmPassword, regexForbidSpecialChars } from 'app/modules/base/helper';
import { Zone } from 'app/modules/zone/services/zone.service';
import { Router } from '@angular/router';
import { RegExs } from '../../base/regex';

@Injectable({
  providedIn: 'root',
})
export class PersonnelService extends APIBase<FormData, Personnel> {
  constructor(protected http: HttpClient, private fb: FormBuilder, private router: Router) {
    super(http, '/api/admin/user');
  }
  // 相关权限
  permission(pid: number) {
    return new APIBase<any, UserPermission>(this.http, `/api/admin/user/${pid}/area`);
  }
  // 删除相关权限
  authDelete(pid: number, zid: number[]) {
    return this.http.request('DELETE', `/api/admin/user/${pid}/area`, { body: zid }).toPromise();
  }
  // 禁止相关权限
  authStatus(pid: number, zid: number[], status: number) {
    return this.http.put(`/api/admin/user/${pid}/area`, { ids: zid, status }).toPromise();
  }
  // 终端使用记录
  usedComputer(uid: number) {
    return new APIBase<any, UsedComputer>(this.http, `/api/admin/user/${uid}/pc_use`);
  }
  // 软件使用记录
  usedSoftware() {
    return new APIBase<any, UsedComputer>(this.http, '/api/admin/logs/human/software');
  }
  // 部门列表
  department() {
    return this.http.get<Department[]>('/api/admin/department').toPromise();
  }
  // 职位列表
  position() {
    return this.http.get<Position[]>('/api/admin/position').toPromise();
  }
  // 批量导入
  import(data: FormData) {
    return this.http.post(this.baseURL + '/import', data).toPromise();
  }
  permissionNav(zone: Zone, pid: number[]) {
    const key = Math.random().toString();
    sessionStorage.setItem(key, pid.join(','));
    this.router.navigate(['zone', 'permission', zone.name], {
      queryParams: { id: zone.id, key },
    });
  }
  // 人员信息表单数据
  get formData() {
    const year = new Date().getFullYear();
    const yearList = new Array(50).fill(0).map((v, i) => year - i);
    const monthList = new Array(12).fill(0).map((v, i) => i + 1);
    const department$ = this.department();
    const position$ = this.position();
    return { yearList, monthList, department$, position$ };
  }
  // 人员信息表单构建
  get formGroup() {
    return this.fb.group(
      {
        id: [],
        utype: [0, Validators.required],
        full_name: ['', Validators.required],
        job_number: [''],
        ldap_username: ['', [Validators.required, Validators.pattern('[a-zA-Z][a-zA-Z0-9_-]{0,30}')]],
        ldap_password: ['', [Validators.required, Validators.minLength(8)]],
        ldap_password_confirm: ['', Validators.required],
        // phone: ['', Validators.pattern(RegExs.PHONE)],
        phone: ['', [Validators.required,  Validators.pattern(RegExs.PHONE)]],
        department_id: [''],
        position_id: [''],
        sex: [0],
        birth_year: [''],
        birth_month: [''],
        email: ['', Validators.email],
        photo: [''],
        remark: [''],
        random_password_switch: false,
      },
      {
        validators: [
          confirmPassword({
            password: 'ldap_password',
            confirm: 'ldap_password_confirm',
          }), 
          regexForbidSpecialChars('full_name')
        ]
      },
    );
  }
  //同步人员数据
  synchronize() {
    return this.http.post('/api/admin/icbc/sync', '').toPromise();
  }
  //查询同步人员进度
  syncStatus(){
    return this.http.get('/api/admin/icbc/sync_notify')
  }
}

interface UsedComputer {
  id: number;
  type: string;
  software_name: string;
  username: string;
  user_number: string;
  name: string;
  ip: string;
  operation: string;
  created_at: string;
}

export interface Personnel {
  id: number;
  full_name: string;
  remark: string;
  utype: number;
  area_count: number;
  policy_count: number;
  status: number;
  update_admin_username: string;
  updated_at_time: string;
  ldap_password: string;
}
export interface PersonnelInfo {
  id: number;
  photo: string;
  ldap_username: string;
  status: number;
  online: boolean;
  updated_at: string;
  created_at: string;
  full_name: string;
  sex: number;
  age: number;
  phone: string;
  email: string;
  utype: number;
  remark: string;
  job_number: string;
  department_id: number;
  position_id: number;
  department_name: string;
  position_name: string;
}

export enum UserStatus {
  Enable,
  Disable,
  DisableInZone,
}
export enum UserType {
  User,
  Admin,
}
export interface UserPermission {
  id: number;
  name: string;
  auth_status: number;
  pc_auth: number;
  pc_config: number;
  software_auth: number;
  update_admin_username: string;
  updated_at_time: string;
}

export interface Department {
  id: number;
  level_struct: string;
  name: string;
  des: string;
}

export interface Position {
  id: number;
  name: string;
}
